package cn.codeforfun.gitee.api.enterprise;

import cn.codeforfun.gitee.api.GiteeService;
import cn.codeforfun.gitee.api.enterprise.bean.GiteeEnterprise;
import cn.codeforfun.gitee.api.enterprise.bean.GiteeGetEnterpriseRequest;
import cn.codeforfun.gitee.api.enterprise.bean.GiteeListEnterpriseRequest;
import cn.codeforfun.gitee.bean.GiteeToken;
import cn.codeforfun.gitee.utils.JsonUtils;
import cn.codeforfun.gitee.utils.OkHttpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

import static cn.codeforfun.gitee.constant.GiteeConstant.URL_PREFIX_API;

/**
 * @author wangbin
 */
@RequiredArgsConstructor
@Slf4j
public class GiteeEnterpriseServiceImpl implements GiteeEnterpriseService {
    private final GiteeService giteeService;

    @Override
    public List<GiteeEnterprise> listEnterprises(GiteeListEnterpriseRequest request) throws IOException {
        GiteeToken token = giteeService.getToken();
        request.setAccessToken(token.getAccessToken());
        giteeService.validate(request);
        log.debug("listEnterprises request:{}", JsonUtils.toJson(request));
        String url = URL_PREFIX_API + "/user/enterprises";
        String result = OkHttpUtils.get(url, request);
        log.debug("listEnterprises result:{}", result);
        return JsonUtils.toBeanList(result, GiteeEnterprise.class);
    }

    @Override
    public GiteeEnterprise getEnterprise(GiteeGetEnterpriseRequest request) throws IOException {
        GiteeToken token = giteeService.getToken();
        request.setAccessToken(token.getAccessToken());
        giteeService.validate(request);
        log.debug("getEnterprise request:{}", JsonUtils.toJson(request));
        String url = URL_PREFIX_API + "/enterprises/"+request.getEnterprise();
        String result = OkHttpUtils.get(url, request);
        log.debug("getEnterprise result:{}", result);
        return JsonUtils.toBean(result, GiteeEnterprise.class);
    }
}
